/**
 * 文件预览组件
 * File Preview Component
 */

class FilePreview {
  constructor(options = {}) {
    this.options = {
      maxImageSize: 10 * 1024 * 1024, // 10MB
      supportedImageTypes: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'],
      supportedVideoTypes: ['mp4', 'webm', 'ogg', 'avi', 'mov'],
      supportedAudioTypes: ['mp3', 'wav', 'ogg', 'aac', 'm4a'],
      supportedDocTypes: ['pdf', 'txt', 'md', 'json', 'xml', 'html', 'css', 'js'],
      ...options
    };
    
    this.currentFile = null;
    this.fileList = [];
    this.currentIndex = 0;
    this.modal = null;
    
    this.init();
  }

  /**
   * 初始化预览组件
   */
  init() {
    this.createModal();
    this.bindEvents();
  }

  /**
   * 创建预览模态框
   */
  createModal() {
    const modal = document.createElement('div');
    modal.id = 'file-preview-modal';
    modal.className = 'fixed inset-0 bg-black bg-opacity-90 flex items-center justify-center z-50 hidden';
    
    modal.innerHTML = `
      <!-- 预览容器 -->
      <div class="relative w-full h-full flex items-center justify-center p-4">
        <!-- 关闭按钮 -->
        <button id="preview-close" class="absolute top-4 right-4 z-10 w-12 h-12 bg-black/50 hover:bg-black/70 rounded-full flex items-center justify-center text-white transition-all">
          <i class="fa fa-times text-xl"></i>
        </button>
        
        <!-- 导航按钮 -->
        <button id="preview-prev" class="absolute left-4 top-1/2 transform -translate-y-1/2 z-10 w-12 h-12 bg-black/50 hover:bg-black/70 rounded-full flex items-center justify-center text-white transition-all">
          <i class="fa fa-chevron-left text-xl"></i>
        </button>
        
        <button id="preview-next" class="absolute right-4 top-1/2 transform -translate-y-1/2 z-10 w-12 h-12 bg-black/50 hover:bg-black/70 rounded-full flex items-center justify-center text-white transition-all">
          <i class="fa fa-chevron-right text-xl"></i>
        </button>
        
        <!-- 预览内容区域 -->
        <div id="preview-content" class="max-w-full max-h-full flex items-center justify-center">
          <!-- 内容将动态插入 -->
        </div>
        
        <!-- 底部信息栏 -->
        <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-6">
          <div class="flex items-center justify-between text-white">
            <div class="flex-1 min-w-0">
              <h3 id="preview-filename" class="text-lg font-semibold truncate mb-1"></h3>
              <div class="flex items-center gap-4 text-sm text-white/80">
                <span id="preview-filesize"></span>
                <span id="preview-filetype"></span>
                <span id="preview-filedate"></span>
              </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="flex items-center gap-2 ml-4">
              <button id="preview-download" class="px-4 py-2 bg-white/20 hover:bg-white/30 rounded-md transition-all flex items-center gap-2">
                <i class="fa fa-download"></i>
                <span>下载</span>
              </button>
              
              <button id="preview-fullscreen" class="px-4 py-2 bg-white/20 hover:bg-white/30 rounded-md transition-all flex items-center gap-2">
                <i class="fa fa-expand"></i>
                <span>全屏</span>
              </button>
            </div>
          </div>
          
          <!-- 进度指示器 -->
          <div class="flex items-center justify-center mt-4">
            <div class="flex items-center gap-2">
              <span id="preview-current" class="text-sm">1</span>
              <span class="text-sm text-white/60">/</span>
              <span id="preview-total" class="text-sm">1</span>
            </div>
          </div>
        </div>
        
        <!-- 加载指示器 -->
        <div id="preview-loading" class="absolute inset-0 flex items-center justify-center bg-black/50 hidden">
          <div class="text-center text-white">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto mb-4"></div>
            <p>加载中...</p>
          </div>
        </div>
        
        <!-- 错误提示 -->
        <div id="preview-error" class="absolute inset-0 flex items-center justify-center bg-black/50 hidden">
          <div class="text-center text-white max-w-md">
            <i class="fa fa-exclamation-triangle text-4xl mb-4 text-yellow-500"></i>
            <h3 class="text-lg font-semibold mb-2">无法预览此文件</h3>
            <p class="text-white/80 mb-4">文件格式不支持或文件已损坏</p>
            <button id="preview-retry" class="px-4 py-2 bg-white/20 hover:bg-white/30 rounded-md transition-all">
              重试
            </button>
          </div>
        </div>
      </div>
    `;
    
    document.body.appendChild(modal);
    this.modal = modal;
  }

  /**
   * 绑定事件
   */
  bindEvents() {
    if (!this.modal) return;
    
    // 关闭按钮
    this.modal.querySelector('#preview-close').addEventListener('click', () => {
      this.close();
    });
    
    // 导航按钮
    this.modal.querySelector('#preview-prev').addEventListener('click', () => {
      this.showPrevious();
    });
    
    this.modal.querySelector('#preview-next').addEventListener('click', () => {
      this.showNext();
    });
    
    // 操作按钮
    this.modal.querySelector('#preview-download').addEventListener('click', () => {
      this.downloadFile();
    });
    
    this.modal.querySelector('#preview-fullscreen').addEventListener('click', () => {
      this.toggleFullscreen();
    });
    
    // 重试按钮
    this.modal.querySelector('#preview-retry').addEventListener('click', () => {
      this.loadCurrentFile();
    });
    
    // 键盘事件
    document.addEventListener('keydown', (e) => {
      if (!this.modal.classList.contains('hidden')) {
        switch (e.key) {
          case 'Escape':
            this.close();
            break;
          case 'ArrowLeft':
            this.showPrevious();
            break;
          case 'ArrowRight':
            this.showNext();
            break;
          case 'f':
          case 'F':
            this.toggleFullscreen();
            break;
        }
      }
    });
    
    // 点击背景关闭
    this.modal.addEventListener('click', (e) => {
      if (e.target === this.modal) {
        this.close();
      }
    });
  }
} 
 /**
   * 预览文件
   */
  async preview(file, fileList = []) {
    this.currentFile = file;
    this.fileList = fileList.length > 0 ? fileList : [file];
    this.currentIndex = this.fileList.findIndex(f => f.id === file.id);
    
    this.show();
    await this.loadCurrentFile();
  }

  /**
   * 显示预览模态框
   */
  show() {
    this.modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
    this.updateNavigation();
    this.updateFileInfo();
  }

  /**
   * 隐藏预览模态框
   */
  close() {
    this.modal.classList.add('hidden');
    document.body.style.overflow = '';
    this.clearContent();
  }

  /**
   * 加载当前文件
   */
  async loadCurrentFile() {
    if (!this.currentFile) return;
    
    this.showLoading();
    this.hideError();
    
    try {
      const fileType = this.getFileType(this.currentFile);
      
      switch (fileType) {
        case 'image':
          await this.loadImage();
          break;
        case 'video':
          await this.loadVideo();
          break;
        case 'audio':
          await this.loadAudio();
          break;
        case 'document':
          await this.loadDocument();
          break;
        default:
          this.showUnsupportedFile();
          break;
      }
      
    } catch (error) {
      console.error('加载文件失败:', error);
      this.showError();
    } finally {
      this.hideLoading();
    }
  }

  /**
   * 加载图片
   */
  async loadImage() {
    const container = this.modal.querySelector('#preview-content');
    
    // 使用静态资源作为示例
    const sampleImages = [
      '/static/image/wallhaven-571je1.webp',
      '/static/image/wallhaven-72pgxv.webp',
      '/static/image/wallhaven-g7gxqq.webp',
      '/static/image/wallhaven-gpp7re.webp',
      '/static/image/wallhaven-n65ew4.webp',
      '/static/image/wallhaven-wq3yop.webp',
      '/static/image/wallhaven-xlo9eo.webp'
    ];
    
    const imageUrl = this.currentFile.url || sampleImages[Math.floor(Math.random() * sampleImages.length)];
    
    return new Promise((resolve, reject) => {
      const img = document.createElement('img');
      img.className = 'max-w-full max-h-full object-contain rounded-lg shadow-2xl';
      img.style.maxHeight = 'calc(100vh - 200px)';
      
      img.onload = () => {
        container.innerHTML = '';
        container.appendChild(img);
        
        // 添加缩放功能
        this.addImageZoom(img);
        resolve();
      };
      
      img.onerror = () => {
        reject(new Error('图片加载失败'));
      };
      
      img.src = imageUrl;
    });
  }

  /**
   * 加载视频
   */
  async loadVideo() {
    const container = this.modal.querySelector('#preview-content');
    
    // 使用静态资源作为示例
    const sampleVideos = [
      '/static/image/56.mp4',
      '/static/image/82.mp4'
    ];
    
    const videoUrl = this.currentFile.url || sampleVideos[Math.floor(Math.random() * sampleVideos.length)];
    
    const video = document.createElement('video');
    video.className = 'max-w-full max-h-full rounded-lg shadow-2xl';
    video.style.maxHeight = 'calc(100vh - 200px)';
    video.controls = true;
    video.autoplay = false;
    video.preload = 'metadata';
    
    // 添加视频源
    const source = document.createElement('source');
    source.src = videoUrl;
    source.type = 'video/mp4';
    video.appendChild(source);
    
    // 添加不支持提示
    video.innerHTML += '您的浏览器不支持视频播放。';
    
    container.innerHTML = '';
    container.appendChild(video);
    
    return Promise.resolve();
  }

  /**
   * 加载音频
   */
  async loadAudio() {
    const container = this.modal.querySelector('#preview-content');
    
    const audioContainer = document.createElement('div');
    audioContainer.className = 'bg-white/10 backdrop-blur-sm rounded-xl p-8 max-w-md w-full';
    
    audioContainer.innerHTML = `
      <div class="text-center mb-6">
        <div class="w-24 h-24 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center mx-auto mb-4">
          <i class="fa fa-music text-white text-3xl"></i>
        </div>
        <h3 class="text-white text-lg font-semibold">${this.currentFile.name}</h3>
      </div>
      
      <audio controls class="w-full">
        <source src="${this.currentFile.url || '#'}" type="audio/mpeg">
        您的浏览器不支持音频播放。
      </audio>
      
      <div class="mt-4 text-center text-white/80 text-sm">
        <p>使用播放控件来控制音频播放</p>
      </div>
    `;
    
    container.innerHTML = '';
    container.appendChild(audioContainer);
    
    return Promise.resolve();
  }

  /**
   * 加载文档
   */
  async loadDocument() {
    const container = this.modal.querySelector('#preview-content');
    
    const docContainer = document.createElement('div');
    docContainer.className = 'bg-white rounded-xl shadow-2xl max-w-4xl w-full max-h-full overflow-hidden';
    
    const fileExt = this.getFileExtension(this.currentFile.name);
    
    if (fileExt === 'pdf') {
      // PDF预览
      docContainer.innerHTML = `
        <div class="p-6 border-b border-neutral-200">
          <div class="flex items-center gap-3">
            <i class="fa fa-file-pdf-o text-red-500 text-2xl"></i>
            <div>
              <h3 class="font-semibold text-neutral-800">${this.currentFile.name}</h3>
              <p class="text-sm text-neutral-600">PDF 文档</p>
            </div>
          </div>
        </div>
        
        <div class="p-6 text-center">
          <iframe src="${this.currentFile.url || '#'}" class="w-full h-96 border border-neutral-200 rounded"></iframe>
          <p class="mt-4 text-neutral-600">如果无法显示，请点击下载按钮下载文件</p>
        </div>
      `;
    } else {
      // 文本文档预览
      docContainer.innerHTML = `
        <div class="p-6 border-b border-neutral-200">
          <div class="flex items-center gap-3">
            <i class="fa fa-file-text-o text-blue-500 text-2xl"></i>
            <div>
              <h3 class="font-semibold text-neutral-800">${this.currentFile.name}</h3>
              <p class="text-sm text-neutral-600">${fileExt.toUpperCase()} 文档</p>
            </div>
          </div>
        </div>
        
        <div class="p-6">
          <div class="bg-neutral-50 rounded-lg p-4 font-mono text-sm max-h-96 overflow-y-auto">
            <pre id="doc-content">正在加载文档内容...</pre>
          </div>
        </div>
      `;
      
      // 模拟加载文档内容
      setTimeout(() => {
        const contentEl = docContainer.querySelector('#doc-content');
        if (contentEl) {
          contentEl.textContent = `这是 ${this.currentFile.name} 的预览内容。\n\n在实际应用中，这里会显示文档的真实内容。\n\n支持的格式包括：\n- 纯文本文件 (.txt)\n- Markdown 文件 (.md)\n- JSON 文件 (.json)\n- XML 文件 (.xml)\n- HTML 文件 (.html)\n- CSS 文件 (.css)\n- JavaScript 文件 (.js)`;
        }
      }, 500);
    }
    
    container.innerHTML = '';
    container.appendChild(docContainer);
    
    return Promise.resolve();
  }
}  /
**
   * 显示不支持的文件类型
   */
  showUnsupportedFile() {
    const container = this.modal.querySelector('#preview-content');
    
    const unsupportedContainer = document.createElement('div');
    unsupportedContainer.className = 'text-center text-white max-w-md';
    
    const fileExt = this.getFileExtension(this.currentFile.name);
    const icon = this.getFileIcon(fileExt);
    
    unsupportedContainer.innerHTML = `
      <div class="w-24 h-24 bg-white/10 rounded-full flex items-center justify-center mx-auto mb-6">
        <i class="fa ${icon} text-4xl"></i>
      </div>
      
      <h3 class="text-xl font-semibold mb-2">${this.currentFile.name}</h3>
      <p class="text-white/80 mb-6">此文件类型暂不支持预览</p>
      
      <div class="flex justify-center gap-3">
        <button id="unsupported-download" class="px-6 py-2 bg-white/20 hover:bg-white/30 rounded-md transition-all flex items-center gap-2">
          <i class="fa fa-download"></i>
          <span>下载文件</span>
        </button>
      </div>
      
      <div class="mt-6 text-sm text-white/60">
        <p>支持预览的格式：</p>
        <p>图片: JPG, PNG, GIF, WebP, SVG</p>
        <p>视频: MP4, WebM, OGG</p>
        <p>音频: MP3, WAV, OGG, AAC</p>
        <p>文档: PDF, TXT, MD, JSON, HTML</p>
      </div>
    `;
    
    container.innerHTML = '';
    container.appendChild(unsupportedContainer);
    
    // 绑定下载事件
    unsupportedContainer.querySelector('#unsupported-download').addEventListener('click', () => {
      this.downloadFile();
    });
  }

  /**
   * 添加图片缩放功能
   */
  addImageZoom(img) {
    let scale = 1;
    let isDragging = false;
    let startX, startY, translateX = 0, translateY = 0;
    
    img.style.cursor = 'grab';
    img.style.transition = 'transform 0.3s ease';
    
    // 鼠标滚轮缩放
    img.addEventListener('wheel', (e) => {
      e.preventDefault();
      
      const delta = e.deltaY > 0 ? 0.9 : 1.1;
      scale *= delta;
      scale = Math.max(0.5, Math.min(3, scale)); // 限制缩放范围
      
      img.style.transform = `scale(${scale}) translate(${translateX}px, ${translateY}px)`;
    });
    
    // 拖拽移动
    img.addEventListener('mousedown', (e) => {
      if (scale > 1) {
        isDragging = true;
        startX = e.clientX - translateX;
        startY = e.clientY - translateY;
        img.style.cursor = 'grabbing';
      }
    });
    
    document.addEventListener('mousemove', (e) => {
      if (isDragging) {
        translateX = e.clientX - startX;
        translateY = e.clientY - startY;
        img.style.transform = `scale(${scale}) translate(${translateX}px, ${translateY}px)`;
      }
    });
    
    document.addEventListener('mouseup', () => {
      isDragging = false;
      img.style.cursor = scale > 1 ? 'grab' : 'default';
    });
    
    // 双击重置
    img.addEventListener('dblclick', () => {
      scale = 1;
      translateX = 0;
      translateY = 0;
      img.style.transform = 'scale(1) translate(0px, 0px)';
    });
  }

  /**
   * 显示上一个文件
   */
  showPrevious() {
    if (this.fileList.length <= 1) return;
    
    this.currentIndex = (this.currentIndex - 1 + this.fileList.length) % this.fileList.length;
    this.currentFile = this.fileList[this.currentIndex];
    
    this.updateNavigation();
    this.updateFileInfo();
    this.loadCurrentFile();
  }

  /**
   * 显示下一个文件
   */
  showNext() {
    if (this.fileList.length <= 1) return;
    
    this.currentIndex = (this.currentIndex + 1) % this.fileList.length;
    this.currentFile = this.fileList[this.currentIndex];
    
    this.updateNavigation();
    this.updateFileInfo();
    this.loadCurrentFile();
  }

  /**
   * 更新导航按钮
   */
  updateNavigation() {
    const prevBtn = this.modal.querySelector('#preview-prev');
    const nextBtn = this.modal.querySelector('#preview-next');
    const currentEl = this.modal.querySelector('#preview-current');
    const totalEl = this.modal.querySelector('#preview-total');
    
    if (this.fileList.length <= 1) {
      prevBtn.style.display = 'none';
      nextBtn.style.display = 'none';
    } else {
      prevBtn.style.display = 'flex';
      nextBtn.style.display = 'flex';
    }
    
    currentEl.textContent = this.currentIndex + 1;
    totalEl.textContent = this.fileList.length;
  }

  /**
   * 更新文件信息
   */
  updateFileInfo() {
    if (!this.currentFile) return;
    
    const filenameEl = this.modal.querySelector('#preview-filename');
    const filesizeEl = this.modal.querySelector('#preview-filesize');
    const filetypeEl = this.modal.querySelector('#preview-filetype');
    const filedateEl = this.modal.querySelector('#preview-filedate');
    
    filenameEl.textContent = this.currentFile.name;
    filesizeEl.textContent = this.formatFileSize(this.currentFile.size || 0);
    filetypeEl.textContent = this.getFileTypeText(this.currentFile);
    filedateEl.textContent = this.formatDate(this.currentFile.modified_at || new Date());
  }

  /**
   * 下载文件
   */
  downloadFile() {
    if (!this.currentFile) return;
    
    const link = document.createElement('a');
    link.href = this.currentFile.url || '#';
    link.download = this.currentFile.name;
    link.style.display = 'none';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // 触发下载事件
    this.dispatchEvent('download', { file: this.currentFile });
  }

  /**
   * 切换全屏
   */
  toggleFullscreen() {
    if (!document.fullscreenElement) {
      this.modal.requestFullscreen().catch(err => {
        console.error('无法进入全屏模式:', err);
      });
    } else {
      document.exitFullscreen();
    }
  }
}  /**
   * 
工具函数
   */
  getFileType(file) {
    const ext = this.getFileExtension(file.name).toLowerCase();
    
    if (this.options.supportedImageTypes.includes(ext)) {
      return 'image';
    } else if (this.options.supportedVideoTypes.includes(ext)) {
      return 'video';
    } else if (this.options.supportedAudioTypes.includes(ext)) {
      return 'audio';
    } else if (this.options.supportedDocTypes.includes(ext)) {
      return 'document';
    }
    
    return 'unknown';
  }

  getFileExtension(filename) {
    return filename.split('.').pop() || '';
  }

  getFileIcon(ext) {
    const iconMap = {
      // 图片
      'jpg': 'fa-file-image-o',
      'jpeg': 'fa-file-image-o',
      'png': 'fa-file-image-o',
      'gif': 'fa-file-image-o',
      'webp': 'fa-file-image-o',
      'svg': 'fa-file-image-o',
      
      // 视频
      'mp4': 'fa-file-video-o',
      'webm': 'fa-file-video-o',
      'ogg': 'fa-file-video-o',
      'avi': 'fa-file-video-o',
      'mov': 'fa-file-video-o',
      
      // 音频
      'mp3': 'fa-file-audio-o',
      'wav': 'fa-file-audio-o',
      'aac': 'fa-file-audio-o',
      'm4a': 'fa-file-audio-o',
      
      // 文档
      'pdf': 'fa-file-pdf-o',
      'txt': 'fa-file-text-o',
      'md': 'fa-file-text-o',
      'json': 'fa-file-code-o',
      'xml': 'fa-file-code-o',
      'html': 'fa-file-code-o',
      'css': 'fa-file-code-o',
      'js': 'fa-file-code-o',
      
      // 压缩文件
      'zip': 'fa-file-archive-o',
      'rar': 'fa-file-archive-o',
      '7z': 'fa-file-archive-o',
      
      // Office文档
      'doc': 'fa-file-word-o',
      'docx': 'fa-file-word-o',
      'xls': 'fa-file-excel-o',
      'xlsx': 'fa-file-excel-o',
      'ppt': 'fa-file-powerpoint-o',
      'pptx': 'fa-file-powerpoint-o'
    };
    
    return iconMap[ext.toLowerCase()] || 'fa-file-o';
  }

  getFileTypeText(file) {
    const ext = this.getFileExtension(file.name).toLowerCase();
    const type = this.getFileType(file);
    
    const typeMap = {
      'image': '图片文件',
      'video': '视频文件',
      'audio': '音频文件',
      'document': '文档文件'
    };
    
    return typeMap[type] || `${ext.toUpperCase()} 文件`;
  }

  formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  }

  /**
   * 状态管理
   */
  showLoading() {
    this.modal.querySelector('#preview-loading').classList.remove('hidden');
    this.modal.querySelector('#preview-error').classList.add('hidden');
  }

  hideLoading() {
    this.modal.querySelector('#preview-loading').classList.add('hidden');
  }

  showError() {
    this.modal.querySelector('#preview-error').classList.remove('hidden');
    this.modal.querySelector('#preview-loading').classList.add('hidden');
  }

  hideError() {
    this.modal.querySelector('#preview-error').classList.add('hidden');
  }

  clearContent() {
    const container = this.modal.querySelector('#preview-content');
    container.innerHTML = '';
  }

  /**
   * 事件分发
   */
  dispatchEvent(eventName, data) {
    const event = new CustomEvent(`filePreview:${eventName}`, {
      detail: data,
      bubbles: true,
      cancelable: true
    });
    
    document.dispatchEvent(event);
    
    // 如果有回调函数，调用它
    const callbackName = `on${eventName.charAt(0).toUpperCase()}${eventName.slice(1)}`;
    if (typeof this.options[callbackName] === 'function') {
      this.options[callbackName](data);
    }
  }

  /**
   * 销毁组件
   */
  destroy() {
    if (this.modal && this.modal.parentNode) {
      this.modal.parentNode.removeChild(this.modal);
    }
    this.modal = null;
    this.currentFile = null;
    this.fileList = [];
  }
}

// 导出文件预览组件
window.FilePreview = FilePreview;